<template>
  <div class="profile-layout">
    <!-- 添加Header组件 -->
    <Header />
    
    <!-- 底层背景 -->
    <div class="background-layer"></div>

    <!-- 顶部菜单栏 -->
    <div class="top-navbar">
      <!-- Logo和标题 -->
      <div class="logo-section">
        <img src="../../assets/images/login/logo2.png" alt="Logo" class="logo-image" />
        <div class="logo-text">
          <span class="logo-title">
            <span class="logo-title-part1">{{ $t('profile.logoTitlePart1') }}</span>
            <span class="logo-title-part2">{{ $t('profile.logoTitlePart2') }}</span>
          </span>
          <span class="logo-subtitle">{{ $t('profile.logoSubtitle') }}</span>
        </div>
      </div>
      
      <!-- 用户信息 -->
      <div class="user-profile-container">
        <!-- 企业需求按钮 -->
        <div class="enterprise-demand-btn">
          <el-button 
            type="primary" 
            @click="goToEnterpriseDemand"
            class="demand-btn"
          >
            <el-icon><Document /></el-icon>
            {{ $t('profile.enterpriseDemand') }}
          </el-button>
        </div>
        <el-dropdown @command="handleUserCommand" trigger="hover">
          <div class="user-avatar">
            <!-- <el-avatar 
              :size="40" 
              :src="userInfo.avatar || '/666.png'" 
              class="avatar-image"
            /> -->
            <span class="username">{{ $t('profile.welcomeUser') }} {{ userInfo.name || $t('profile.user') }}</span>
            <i class="el-icon-arrow-down el-icon--right"></i>
          </div>
          <template #dropdown>
            <!-- <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item command="settings">
                <el-icon><Setting /></el-icon>
                设置
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                退出
              </el-dropdown-item>
            </el-dropdown-menu> -->
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 左侧导航栏 -->
    <div class="left-navbar">
      <!-- 返回按钮 -->
      <div class="back-button-container">
        <el-button 
          link 
          @click="goBack"
          class="back-button"
          size="small"
        >
          <el-icon><ArrowLeft /></el-icon>
          <span>{{ $t('profile.back') }}</span>
        </el-button>
      </div>
      
      <!-- Logo 区域 -->
      <!-- <div class="logo-container">
        <img src="/666.png" alt="Logo" class="navbar-logo" />
      </div> -->
      
      <div class="nav-menu">
        <div class="nav-item" @click="switchContent('resume')" :class="{ active: currentContent === 'resume' }">
          <div class="nav-label">{{ $t('profile.myResume') }}</div>
        </div>
        <div class="nav-item" @click="switchContent('applications')" :class="{ active: currentContent === 'applications' }">
          <div class="nav-label">{{ $t('profile.myApplications') }}</div>
        </div>
        <div class="nav-item" @click="switchContent('messages')" :class="{ active: currentContent === 'messages' }">
          <div class="nav-label">
            {{ $t('profile.messageCenter') }}
            <div v-if="unreadMessageCount > 0" class="nav-indicator-dot"></div>
          </div>
        </div>
        <div class="nav-item" @click="switchContent('settings')" :class="{ active: currentContent === 'settings' }">
          <div class="nav-label">{{ $t('profile.accountSettings') }}</div>
        </div>
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="main-container">
      <!-- 简历内容 -->
      <div v-if="currentContent === 'resume'" class="content-panel">
        <!-- 简历列表视图 -->
        <div v-if="!selectedResume" class="resume-list-view">
          <ResumeList 
            @select-resume="handleSelectResume"
            @create-resume="handleCreateResume"
          />
        </div>
        <!-- 简历编辑视图 -->
        <div v-else class="resume-edit-view">
          <div class="edit-header">
            <el-button 
              link 
              @click="backToResumeList"
              class="back-to-list-btn"
            >
              <el-icon><ArrowLeft /></el-icon>
              {{ $t('profile.backToResumeList') }}
            </el-button>
            <div class="edit-title">
              {{ selectedResume.isNewResume ? $t('profile.newResume') : $t('profile.editResume') }}
            </div>
          </div>
          <div class="edit-content-container">
            <div class="edit-panel">
              <div class="edit-content">
                <ResumeForm 
                  :key="selectedResume.id"
                  :is-new="selectedResume.isNewResume"
                  :resume-status="selectedResume.status"
                />
              </div>
            </div>
            <div class="preview-panel">
              <div class="preview-content">
                <ResumePreview 
                  :key="selectedResume.id"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 申请内容 -->
      <div v-if="currentContent === 'applications'" class="content-panel">
        <Applications />
      </div>

      <!-- 消息内容 -->
      <div v-if="currentContent === 'messages'" class="content-panel">
        <Message @message-read="fetchUnreadMessageCount" />
      </div>

      <!-- 设置内容 -->
      <div v-if="currentContent === 'settings'" class="content-panel">
        <Settings />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Document, User, Setting, SwitchButton } from '@element-plus/icons-vue'
import { studentApi, systemApi, userApi } from '../../api/index.js'
import { notificationsApi } from '../../api/notifications.js'
import ResumeForm from '../../components/resume/ResumeForm.vue'
import ResumePreview from '../../components/resume/ResumePreview.vue'
import ResumeList from '../../components/resume/ResumeList.vue'
import Applications from '../duijie/Applications.vue'
import Message from '../xiaoxiyoujian/Message.vue'
import AccountSettings from '../../components/settings/AccountSettings.vue'
import Header from '../../components/layout/Header.vue'

// 账号设置组件
const Settings = AccountSettings

const router = useRouter()
const route = useRoute()
const { t } = useI18n()

// 当前显示的内容
const currentContent = ref('resume')

// 选中的简历
const selectedResume = ref(null)

// 切换内容
function switchContent(content) {
  currentContent.value = content
  // 切换到其他模块时，清空选中的简历
  if (content !== 'resume') {
    selectedResume.value = null
  }
  // 切换到消息中心时，刷新未读消息数量
  if (content === 'messages') {
    fetchUnreadMessageCount()
  }
}

// 处理选择简历
function handleSelectResume(resume) {
  // 确保简历数据包含状态信息
  selectedResume.value = {
    ...resume,
    // 如果简历数据中没有状态，尝试获取最新状态
    status: resume.status || 'pending'
  }
}

// 处理新建简历
function handleCreateResume() {
  selectedResume.value = {
    id: 'new',
    title: t('profile.newResume'),
    isNew: true,
    isNewResume: true // 标记这是新建简历
  }
}

// 返回简历列表
function backToResumeList() {
  selectedResume.value = null
}

// 返回上一页
function goBack() {
  router.go(-1)
}

// 跳转到企业需求页面
function goToEnterpriseDemand() {
  router.push('/use/enterprise-demand')
}

// 处理用户下拉菜单命令
function handleUserCommand(command) {
  if (command === 'profile') {
    // 跳转到个人中心
    router.push('/gerenzhongxin/profile')
  } else if (command === 'settings') {
    // 跳转到设置页面
    router.push('/gerenzhongxin/settings')
  } else if (command === 'logout') {
    // 退出登录
    ElMessage.success(t('profile.logoutSuccess'))
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push('/login')
  }
}

// 用户信息
const userInfo = ref({
  name: '',
  email: '',
  avatar: '',
  status: '离线',
  nationality: '',
  gender: '',
  birthDate: '',
  phone: '',
  wechat: '',
  whatsapp: ''
})

// 加载状态
const loading = ref(false)

// 国籍选项
const nationalityOptions = ref([])

// 未读消息数量
const unreadMessageCount = ref(0)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    loading.value = true
    
    // 从简历接口获取用户信息（这个接口权限正常）
    const resumeResponse = await studentApi.getResume()
    
    if (resumeResponse.code === 200 && resumeResponse.data) {
      // 简历数据存在，使用简历数据
      const data = resumeResponse.data
      userInfo.value = {
        name: data.fullName || t('profile.unknownUser'),
        email: data.email || '',
        avatar: '', // 简历接口暂时不返回头像
        status: t('profile.online'),
        nationality: data.nationality || '',
        gender: data.gender || '',
        birthDate: data.dateOfBirth || '',
        phone: data.phoneNumber || '',
        wechat: data.wechatWhatsapp || '', // 暂时使用wechatWhatsapp字段
        whatsapp: '' // 暂时为空
      }
    } else if (resumeResponse.code === 404) {
      // 新用户，简历数据不存在，这是正常状态
      userInfo.value = {
        name: t('profile.unknownUser'),
        email: '',
        avatar: '',
        status: t('profile.online'),
        nationality: '',
        gender: '',
        birthDate: '',
        phone: '',
        wechat: '',
        whatsapp: ''
      }
    } else {
      // 其他错误，使用默认值
      userInfo.value = {
        name: t('profile.unknownUser'),
        email: '',
        avatar: '',
        status: t('profile.online'),
        nationality: '',
        gender: '',
        birthDate: '',
        phone: '',
        wechat: '',
        whatsapp: ''
      }
    }
  } catch (error) {
    // 网络错误等，使用默认值
    userInfo.value = {
      name: t('profile.unknownUser'),
      email: '',
      avatar: '',
      status: t('profile.online'),
      nationality: '',
      gender: '',
      birthDate: '',
      phone: '',
      wechat: '',
      whatsapp: ''
    }
  } finally {
    loading.value = false
  }
}

// 获取国籍列表
const loadNationalities = async () => {
  // 如果已经加载过，就不再重复加载
  if (nationalityOptions.value.length > 0) {
    return
  }
  
  try {
    
    
    // 首先尝试学生端专用API
    let response = await studentApi.getNationalities()
    
    
    // 如果学生端API失败，尝试通用API
    if (!response || response.code !== 'SUCCESS' || !response.data) {
      response = await systemApi.getNationalities()
    }
    
    if ((response.code === 'SUCCESS' || response.code === 200) && response.data && Array.isArray(response.data)) {
      nationalityOptions.value = response.data.map(item => ({
        value: item.value,
        label: item.label
      }))

    } else {
      console.warn('个人中心 - 国籍API返回格式异常，使用默认列表')
      // 如果接口失败，使用默认国籍列表
      nationalityOptions.value = [
        { value: 1, label: t('profile.nationalityChina') },
        { value: 2, label: t('profile.nationalityUSA') },
        { value: 3, label: t('profile.nationalityUK') },
        { value: 4, label: t('profile.nationalityCanada') },
        { value: 5, label: t('profile.nationalityAustralia') },
        { value: 6, label: t('profile.nationalityJapan') },
        { value: 7, label: t('profile.nationalityKorea') },
        { value: 8, label: t('profile.nationalityGermany') },
        { value: 9, label: t('profile.nationalityFrance') },
        { value: 10, label: t('profile.nationalitySingapore') },
        { value: 11, label: t('profile.nationalityMalaysia') },
        { value: 12, label: t('profile.nationalityThailand') },
        { value: 13, label: t('profile.nationalityVietnam') },
        { value: 14, label: t('profile.nationalityIndia') },
        { value: 15, label: t('profile.nationalityRussia') },
        { value: 16, label: t('profile.nationalityOther') }
      ]
    }
  } catch (error) {
    console.error('个人中心 - 加载国籍列表失败:', error)
    // 如果接口失败，使用默认国籍列表
    nationalityOptions.value = [
      { value: 1, label: t('profile.nationalityChina') },
      { value: 2, label: t('profile.nationalityUSA') },
      { value: 3, label: t('profile.nationalityUK') },
      { value: 4, label: t('profile.nationalityCanada') },
      { value: 5, label: t('profile.nationalityAustralia') },
      { value: 6, label: t('profile.nationalityJapan') },
      { value: 7, label: t('profile.nationalityKorea') },
      { value: 8, label: t('profile.nationalityGermany') },
      { value: 9, label: t('profile.nationalityFrance') },
      { value: 10, label: t('profile.nationalitySingapore') },
      { value: 11, label: t('profile.nationalityMalaysia') },
      { value: 12, label: t('profile.nationalityThailand') },
      { value: 13, label: t('profile.nationalityVietnam') },
      { value: 14, label: t('profile.nationalityIndia') },
      { value: 15, label: t('profile.nationalityRussia') },
      { value: 16, label: t('profile.nationalityOther') }
    ]
  }
}

// 保存个人信息
const saveProfile = async () => {
  try {
    loading.value = true
    
    // 构建简历数据格式
    const resumeData = {
      fullName: userInfo.value.name,
      nationality: userInfo.value.nationality,
      gender: userInfo.value.gender,
      dateOfBirth: userInfo.value.birthDate,
      phoneNumber: userInfo.value.phone,
      email: userInfo.value.email,
      wechatWhatsapp: userInfo.value.wechat, // 暂时只保存微信
      resumeContent: '', // 暂时为空
      educationList: [{
        major: '',
        degree: ''
      }],
      languagesList: [],
      skillsList: []
    }
    
    // 使用简历接口保存个人信息
    const response = await studentApi.updateResume(resumeData)
    
    if (response.code === 200) {
      ElMessage.success(t('profile.profileSaveSuccess'))
      // 更新本地存储
      localStorage.setItem('user', JSON.stringify(userInfo.value))
    } else {
      ElMessage.error(response.message || t('profile.saveFailed'))
    }
  } catch (error) {
    ElMessage.error(t('profile.networkError'))
  } finally {
    loading.value = false
  }
}

// 获取未读消息数量
const fetchUnreadMessageCount = async () => {
  try {
    const response = await notificationsApi.getUnreadCount()
    if (response.code === 200) {
      unreadMessageCount.value = response.data || 0
    } else {
      unreadMessageCount.value = 0
      console.warn('获取未读消息数量失败:', response.message)
    }
  } catch (error) {
    // 如果API调用失败，暂时设置为0
    unreadMessageCount.value = 0
    console.warn('获取未读消息数量失败，可能是通知服务未启动:', error.message)
    
    // 如果是404错误，说明通知服务不存在，可以忽略
    if (error.response && error.response.status === 404) {
      console.log('通知服务不存在，跳过未读消息获取')
    }
  }
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
  fetchUnreadMessageCount()
  
  // 检查URL参数，自动切换到指定标签页
  const tab = route.query.tab
  if (tab && ['resume', 'applications', 'messages', 'settings'].includes(tab)) {
    switchContent(tab)
  }
})
</script>

<style scoped>
.profile-layout {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: #f5f5f5;
  display: flex;
}

/* 底层背景 */
.background-layer {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5;
  z-index: -1;
}

/* 顶部菜单栏 */
.top-navbar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 80px;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

/* Logo和标题部分 */
.logo-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.logo-image {
  width: 40px;
  height: 40px;
  object-fit: contain;
  border-radius: 8px;
}

.logo-text {
  display: flex;
  flex-direction: column;
}

.logo-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.logo-title-part1 {
  color: #007bff;
}

.logo-title-part2 {
  color: #666;
}

.logo-subtitle {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

/* 用户信息部分 */
.user-profile-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.enterprise-demand-btn {
  margin-right: 15px;
}

.demand-btn {
  background-color: #409eff;
  border-color: #409eff;
  color: #fff;
  padding: 8px 15px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.demand-btn:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  color: #fff;
}

.user-avatar {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 10px;
  padding: 8px 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
  background-color: #ffffff;
}

.user-avatar:hover {
  background-color: #f0f7fa;
}

.avatar-image {
  border: 2px solid #409eff;
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: #000000;
}

.el-icon-arrow-down {
  font-size: 14px;
  color: #999;
}

/* 左侧导航栏 */
.left-navbar {
  width: 10%;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0 40px 0;
  z-index: 10;
  flex-shrink: 0;
  border-right: 1px solid #e5e5e5;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  margin-top: 80px; /* 为顶部菜单栏留出空间 */
}

/* 返回按钮容器 */
.back-button-container {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 10px 15px;
  margin-bottom: 10px;
}

/* 返回按钮 */
.back-button {
  color: #666;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
}

.back-button:hover {
  background-color: #f5f5f5;
  color: #007bff;
}

.back-button .el-icon {
  font-size: 16px;
}

/* Logo 容器 */
.logo-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  padding: 10px;
}

/* Logo 图片 */
.navbar-logo {
  width: 60px;
  height: 60px;
  object-fit: contain;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.nav-menu {
  display: flex;
  flex-direction: column;
  gap: 20px;
  width: 100%;
  align-items: center;
}

.nav-item {
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  padding: 0 20px;
  border-radius: 8px;
  margin: 0 10px;
}

.nav-icon {
  font-size: 18px;
  margin-right: 8px;
  color: #666;
  transition: all 0.3s ease;
}

.nav-label {
  font-size: 0.9rem;
  color: #666;
  font-weight: 400;
  transition: all 0.3s ease;
  position: relative;
  display: flex;
  align-items: center;
  gap: 8px;
}

.nav-indicator-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ff4d4f;
  flex-shrink: 0;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(255, 77, 79, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(255, 77, 79, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(255, 77, 79, 0);
  }
}

.nav-item:hover {
  background: #f8f9fa;
  transform: translateX(2px);
}

.nav-item.active {
  background: linear-gradient(135deg, #e3f2fd 0%, #f0f8ff 100%);
  box-shadow: 0 2px 8px rgba(0, 123, 255, 0.15);
}

.nav-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 60%;
  background: linear-gradient(135deg, #007bff, #0056b3);
  border-radius: 0 2px 2px 0;
}

.nav-item.active .nav-icon,
.nav-item.active .nav-label {
  color: #007bff;
  font-weight: 500;
}

/* 主内容区域 */
.main-container {
  flex: 1;
  height: 100vh;
  position: relative;
  background: #f5f5f5;
  padding: 20px;
  overflow: hidden;
  margin-top: 80px; /* 为顶部菜单栏留出空间 */
}

/* 内容面板 */
.content-panel {
  width: 100%;
  height: 100%;
  display: flex;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 简历内容 - 左侧编辑面板 */
.edit-panel {
  width: 45%;
  min-width: 400px;
  background: #ffffff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

.edit-panel::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 1px;
  height: 100%;
  background: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.05), transparent);
}

.edit-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 30px;
  height: 100%;
}

/* 简历内容 - 右侧预览面板 */
.preview-panel {
  width: 55%;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 预览面板内容 */
.preview-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 30px;
  height: 100%;
}

/* 非简历页面的内容样式 */
.content-panel > *:not(.edit-panel):not(.preview-panel) {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
}

/* 滚动条样式优化 */
.edit-content::-webkit-scrollbar,
.preview-content::-webkit-scrollbar {
  width: 6px;
}

.edit-content::-webkit-scrollbar-track,
.preview-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.edit-content::-webkit-scrollbar-thumb,
.preview-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.edit-content::-webkit-scrollbar-thumb:hover,
.preview-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 简历列表视图 */
.resume-list-view {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 12px;
  overflow: hidden;
}

/* 简历编辑视图 */
.resume-edit-view {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.edit-content-container {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.edit-header {
  padding: 20px 30px 0;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-to-list-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #409eff;
  font-size: 14px;
}

.edit-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.back-to-list-btn:hover {
  color: #66b1ff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-navbar {
    width: 12%;
  }
  
  .edit-panel {
    width: 50%;
  }
  
  .preview-panel {
    width: 50%;
  }
}

@media (max-width: 768px) {
  .left-navbar {
    width: 15%;
  }
  
  .main-container {
    padding: 10px;
  }
  
  .content-panel {
    border-radius: 8px;
  }
}
</style> 